import { getOneIdAccessToken, getOneIdAccessUserInfo } from '@/services/login/oneId';
import { getQueryString } from '@/utils/IDaaS';
import { history, useModel } from '@umijs/max';
import { notification } from 'antd';
import React, { useEffect } from 'react';
import { flushSync } from 'react-dom';

const Login2: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  useEffect(() => {
    init();
  }, []);

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    // debugger;
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  async function init() {
    let BASE_URL = 'https://oneid.siemens.com.cn';
    let IDAAS_APP_ID = 'siemens_ciam30';
    const code = getQueryString();
    if (!code) {
      window.location.replace(`${BASE_URL}?idaasAppId=${IDAAS_APP_ID}`);
      return;
    }

    const SDK = new IDaaSLoginSDK({
      baseUrl: BASE_URL,
      idaasAppId: IDAAS_APP_ID,
      async loginSuccess(data) {
        debugger;

        console.log('loginSuccess', data);
      },
      // 切换语言函数
      async changeLanguageCallback(data) {
        alert('切换语言：' + JSON.stringify(data));
        console.log('changeLanguage', data);
      },
    });

    // 请求token
    let token = await getOneIdAccessToken({
      code: code,
      redirectUri: '',
      codeVerifier: '',
      scope: '',
    });

    let oneIdToken = JSON.parse(token.data);

    console.log(oneIdToken, '---taken.data--');

    if (oneIdToken.success != true) {
      notification.error({
        description: oneIdToken.message,
        message: '报错',
      });
      history.push({
        pathname: `/user/Login`,
        // query: {
        //   dictionaryId: record.id,
        // },
      });
      return;
    }

    //todo:这个暂时不需要
    // sessionStorage.setItem('bctoken', JSON.stringify('ThirdPart' + oneIdToken.data.access_token));

    let result = await getOneIdAccessUserInfo({
      accessToken: oneIdToken.data.access_token,
    });

    //获取转换之后的token
    sessionStorage.setItem('bctoken', JSON.stringify(result.data.access_token));

    console.log(result, '----result---');
    let userTokenInfo = {
      success: true,
      code: 'Operation.Success',
      message: 'Operation.Success',
      requestId: '1646656618881$dd57e979-eba7-b83d-f780-f3e7a1925b1d',
      data: {
        access_token: 'eyJhbGciOiJLBOzQ',
        token_type: 'bearer',
        refresh_token: 'eyJhbGcic87nWvVQ',
        expires_in: 7199,
        scope: 'read',
        id_token: 'eyJhbGciILmg',
      },
    };
    const newUserTokenInfo = { ...userTokenInfo, ...oneIdToken };
    // console.log(JSON.parse(token.message));
    // await SDK.initUserToken();
    await SDK.clearUserToken();
    await SDK.initUserToken(newUserTokenInfo);
    const res = await SDK.getUserToken();
    console.log(res.data);
    let userInfo = {
      access_token: res.data.access_token,
      token_type: newUserTokenInfo.data.token_type,
      refresh_token: newUserTokenInfo.data.refresh_token,
      expires_in: newUserTokenInfo.data.expires_in,
      login_type: 'ONE_ID',
    };

    //完成跳转
    console.log(userInfo, '---userInfo---');

    sessionStorage.setItem('OneId', JSON.stringify(userInfo));
    await fetchUserInfo();
    const urlParams = new URL(window.location.href).searchParams;
    history.push(urlParams.get('redirect') || '/welcome');
  }

  return <div className="oneID-login-page"></div>;
};

export default Login2;
